//
//  LibraryViewController.m
//  iSURFCompare
//
//  Created by Vinh Huynh on 5/17/13.
//  Copyright (c) 2013 Aptogo Limited. All rights reserved.
//

#import "LibraryViewController.h"
#import <AVFoundation/AVAudioPlayer.h>

#define BARBUTTON(TITLE, SELECTOR) 	[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

@interface LibraryViewController () <UITableViewDataSource, UITableViewDelegate, AVAudioPlayerDelegate>
{
    NSArray				*fileList;
	AVAudioPlayer		*player;
}
@end

@implementation LibraryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Records";
    // Do any additional setup after loading the view from its nib.
    [self loadFileList];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_recordTb release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setRecordTb:nil];
    [super viewDidUnload];
}

- (void) loadFileList
{
    NSArray *matchArray = [NSArray arrayWithObject:@"aif"];
    NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:DOCUMENTS_FOLDER error:nil];
	fileList = [[NSArray alloc] initWithArray:[contents pathsMatchingExtensions:matchArray]];
    [_recordTb reloadData];
}

- (void) viewWillDisappear:(BOOL) animated
{
	// Pause playback before leaving this view
	if (player)
	{
		[player stop];
		player = nil;
	}
	[super viewWillDisappear: animated];
}

- (void) viewWillAppear: (BOOL) animated
{
	// Update the table to display any new items
	[self.recordTb reloadData];
	if ([self.recordTb indexPathForSelectedRow])
		[self.recordTb deselectRowAtIndexPath:[self.recordTb indexPathForSelectedRow] animated:YES];
}

// utility
- (void) deselect
{
	[self.recordTb deselectRowAtIndexPath:[self.recordTb indexPathForSelectedRow] animated:YES];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)aPlayer successfully:(BOOL)flag
{
	player = nil;
}

// Respond to user selection by playing the audio
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath // fromIndexPath:(NSIndexPath *)oldIndexPath
{
	NSString *path = [DOCUMENTS_FOLDER stringByAppendingPathComponent:[fileList objectAtIndex:[newIndexPath row]]];
	
	// Finish any previous playback
	if (player)
		[player stop];
    
	player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
	player.delegate = self;
	[player play];
}


// Editing
-(void)enterEditMode
{
	if ([self.recordTb indexPathForSelectedRow]) [self.recordTb deselectRowAtIndexPath:[self.recordTb indexPathForSelectedRow] animated:YES];
	self.navigationItem.rightBarButtonItem = BARBUTTON(@"Done", @selector(leaveEditMode));
	[self.recordTb setEditing:YES animated:YES];
}

-(void)leaveEditMode
{
	self.navigationItem.rightBarButtonItem = BARBUTTON(@"Edit", @selector(enterEditMode));
	[self.recordTb setEditing:NO animated:YES];
}

// Delete the selected file
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *path = [DOCUMENTS_FOLDER stringByAppendingPathComponent:[fileList objectAtIndex:[indexPath row]]];
	[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
	[self loadFileList];
	[self.recordTb reloadData];
}

// Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return fileList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@",[fileList objectAtIndex:indexPath.row]];
    return cell;
}

// View initialization
- (void) loadView
{
	[super loadView];
	self.recordTb.rowHeight = 48.0f;
	self.navigationItem.rightBarButtonItem = BARBUTTON(@"Edit", @selector(enterEditMode));
}
@end
